import axios from 'axios'
import {Toast, Dialog} from "vant";
import common from '../assets/js/common';
import Qs from 'qs';
import store from '../store/';
import router from "@/router";

axios.defaults.timeout = 30000;                        //响应时间1


let baseUrl = '';
const isPro = Object.is(process.env.NODE_ENV, 'production')
let wx_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc77ff79c14e0b560&redirect_uri=http%3A%2F%2Fwww.z286.com.cn%2Fweb%2F%23%2Flogin_api&response_type=code&scope=snsapi_base&state=userinfo'
let xiangmu = '/web/#/'
if(isPro){
    baseUrl = 'https://www.z286.com.cn/api/'
}
else{
    baseUrl = 'https://www.z286.com.cn/api/'
}
axios.defaults.baseURL = baseUrl;

//POST传参序列化(添加请求拦截器)
axios.interceptors.request.use((config) => {
    //在发送请求之前做某件事
    //携带请求头

    let token = store.state.token

    if(router.history.current.query.token){
        token = router.history.current.query.token;
    }

    config.headers['Authorization'] = token
    return config;
},(error) =>{
    console.log('错误的传参')
    return Promise.reject(error);
});

//返回状态判断(添加响应拦截器)
axios.interceptors.response.use((res) =>{
    //对响应数据做些事
    if(!res.data.success){
        return Promise.resolve(res);
    }
    return res;
}, (error) => {
    Toast('网络异常');
    return Promise.reject(error);
});

//返回一个Promise(发送post请求)
export function fetchPost(url, params) {
    common.toast_loading();
    return new Promise((resolve, reject) => {
        axios.post(url, Qs.stringify(params),{
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            }
        })
            .then(response => {
                if(response.data.code == 0 || (response.data.code > 2000 && response.data.code < 3000)){
                    resolve(response.data)
                    common.toast_clear()
                }
                else{
                    if(response.data.code == 401){
                        Dialog.alert({
                            title: '请登录',
                            message:
                                '您的未登录，无法进行操作，请您重新登录',
                        })
                            .then(() => {
                                router.push('/isLogin')
                            })
                    }

                    Toast(response.data.msg);
                    setTimeout(() => {
                        common.toast_clear()
                        // resolve(response.data)
                    },1000)
                }

            }, err => {
                reject(err);
                common.toast_clear();
            })
            .catch((error) => {
                reject(error);
                common.toast_clear();
            })
    })
}
///返回一个Promise(发送get请求)
export function fetchGet(url, param) {
    common.toast_loading();
    return new Promise((resolve, reject) => {
        axios.get(url, {params: param},{
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            }
        })
            .then(response => {
                if(response.data.code == 0 || (response.data.code > 2000 && response.data.code < 3000) || response.data.imageUrl != null){
                    resolve(response.data)
                }
                else{
                    if(response.data.code == 401){
                        Dialog.alert({
                            title: '请登录',
                            message:
                                '您的未登录，无法进行操作，请您重新登录',
                        })
                        .then(() => {
                            router.push('/isLogin')
                        })
                    }
                    Toast(response.data.msg);
                    return;
                }
                common.toast_clear();
            }, err => {
                reject(err);
                common.toast_clear();
            })
            .catch((error) => {
                reject(error);
                common.toast_clear();
            })
    })
}

///返回一个Promise(发送get请求)
export function fetchGet_pdf(url, param) {
    common.toast_loading();
    return new Promise((resolve, reject) => {
        axios.get(url, {responseType: 'blob'},{
            headers: {
                'Content-Type': 'application/pdf'
            }
        })
            .then(response => {
                // if(response.data.type == 'application/pdf'){
                    resolve(response)
                // }
                // else{
                //     Toast('参数出现问题，请正确下载。');
                // }
                common.toast_clear();
            }, err => {

                reject(err);
                common.toast_clear();
            })
            .catch((error) => {

                reject(error);
                common.toast_clear();
            })
    })
}

export function fetchGet_pdf2(url, param,token) {
    common.toast_loading();
    return new Promise((resolve, reject) => {
        axios.get(url, {responseType: 'blob'},{
            headers: {
                'Content-Type': 'application/pdf',
                'Authorization' : token
            }
        })
            .then(response => {
                // if(response.data.type == 'application/pdf'){
                resolve(response)
                // }
                // else{
                //     Toast('参数出现问题，请正确下载。');
                // }
                common.toast_clear();
            }, err => {

                reject(err);
                common.toast_clear();
            })
            .catch((error) => {

                reject(error);
                common.toast_clear();
            })
    })
}

///返回一个Promise(发送post from_data)
export function fetchPost_formdata(url, param) {
    return new Promise((resolve, reject) => {
        axios.post(url, param,{
            headers: {
                "Content-Type": "multipart/form-data"
            }
        })
            .then(response => {
                if(response.data.code == 0){
                    resolve(response.data)
                }
                else{
                    Toast(response.data.msg);
                    return;
                }
            }, err => {
                reject(err)
            })
            .catch((error) => {
                reject(error)
            })
    })
}

export function moreHttp(option) {
    let arr = [],
        keys = [];
    for (let key in option) {
        keys.push(key);
        arr.push(option[key]);
    }
    return Axios.all(arr).then(
        Axios.spread(function () {
            let result = {};
            for (let i = 0; i < arguments.length; i++) {
                let item = arguments[i];
                if (item) {
                    if (item.data && item.data.data) {
                        result[keys[i]] = item.data.data;
                    } else {
                        result[keys[i]] = item;
                    }
                }
            }
            return result;
        })
    );
}

export default {
    fetchPost,
    fetchGet,
    fetchPost_formdata,
    moreHttp,
    wx_url,
    xiangmu,
    fetchGet_pdf,
    fetchGet_pdf2,
    baseUrl
}
